package org.misty.blog.controller;

import org.misty.blog.po.Article;
import org.misty.blog.po.Tag;
import org.misty.blog.service.ArticleService;
import org.misty.blog.service.TagService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class TagViewController {
    private final ArticleService articleService;
    private final TagService tagService;

    public TagViewController(ArticleService articleService, TagService tagService) {
        this.articleService = articleService;
        this.tagService = tagService;
    }

    @GetMapping("/tags")
    public String tagsView(
            @PageableDefault(size = 2, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
            @RequestParam(required = false) Long tagId,
            Model model
    ) {
        List<Tag> tags = tagService.listTop(Integer.MAX_VALUE);
        model.addAttribute("tags", tags);
        if (tagId == null && tags.size() > 0) {
            tagId = tags.get(0).getId();
        }
        if (tagId != null) {
            model.addAttribute("tagId", tagId);
            Page<Article> page = articleService.listArticlesByTagId(pageable, tagId);

            model.addAttribute("page", page);
            model.addAttribute("articles", page.getContent());
        }
        return "tags";
    }
}
